package cz.none.bezbarier.web.controller;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cz.none.bezbarier.web.util.Constants;
import cz.none.bezbarier.web.vo.FlashMessage.Severity;

@Controller
public class LoginController extends AController {

	private static final Logger LOG = LoggerFactory.getLogger(LoginController.class);

	@RequestMapping(value = Constants.Page.LOGIN_M, method = RequestMethod.GET)
	public String renderlogin(@RequestParam(value = "error", required = false) boolean error,
			HttpSession session, Model model) {
		setActiveMenu(model, Constants.Menu.LOGIN);

		if (error) {
			AuthenticationException e = (AuthenticationException) session
					.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);

			if (e instanceof BadCredentialsException) {
				addFlashMessage(model, Severity.ERROR, "login.error.default", new Object[] {});
			} else if (e instanceof DisabledException) {
				addFlashMessage(model, Severity.ERROR, "login.error.disabled", new Object[] {});
			} else if (e instanceof LockedException) {
				addFlashMessage(model, Severity.ERROR, "login.error.locked", new Object[] {});
			} else {
				addFlashMessage(model, Severity.ERROR, "login.error.default", new Object[] {});
			}

			LOG.info("User login failed", e);
		}

		return Constants.Page.LOGIN;
	}

	@RequestMapping(value = Constants.Page.DENIED_M, method = RequestMethod.GET)
	public String getDeniedPage() {

		// This will resolve to /WEB-INF/jsp/deniedpage.jsp
		return Constants.Page.DENIED;
	}
}
